#/src/views/CurrencyView.py
from flask import request, g, Blueprint, json, Response
from shared.Authentication import Auth
from models import CurrencyModel, CurrencySchema

currency_api = Blueprint('currency_api', __name__)
currency_schema = CurrencySchema()


@currency_api.route('/', methods=['POST'])
@Auth.auth_required
def create():
  """
  Create Currency Function
  """
  req_data = request.get_json()
  data, error = currency_schema.load(req_data)  # {'title': 'Second POST', 'contents': 'This is my second post', 'owner_id': 2}
  if error:

    return custom_response(error, 400)
  post = CurrencyModel(data)
  post.save()
  data = currency_schema.dump(post).data  # {'title': 'Second POST', 'id': 2, 'created_at': '2020-06-23T14:10:20.194070+00:00', 'contents': 'This is my second post', 'owner_id': 2, 'modified_at': '2020-06-23T14:10:20.194070+00:00'}
  
  return custom_response(data, 201)

@currency_api.route('/', methods=['GET'])
def get_all():
  """
  Get All Currencies
  """
  posts = CurrencyModel.get_all_currencies()
  data = currency_schema.dump(posts, many=True).data
  return custom_response(data, 200)

@currency_api.route('/<int:currency_id>', methods=['GET'])
def get_one(currency_id):
  """
  Get A Currency
  """
  post = CurrencyModel.get_one_currency(currency_id)
  if not post:
    return custom_response({'error': 'post not found'}, 404)
  data = currency_schema.dump(post).data
  return custom_response(data, 200)

@currency_api.route('/<int:currency_id>', methods=['PUT'])
@Auth.auth_required
def update(currency_id):
  """
  Update A Currency
  """
  req_data = request.get_json()
  post = CurrencyModel.get_one_currency(currency_id)
  if not post:
    return custom_response({'error': 'post not found'}, 404)
  data = currency_schema.dump(post).data

  data, error = currency_schema.load(req_data, partial=True)
  if error:
    return custom_response(error, 400)
  post.update(data)
  
  data = currency_schema.dump(post).data
  return custom_response(data, 200)

@currency_api.route('/<int:currency_id>', methods=['DELETE'])
@Auth.auth_required
def delete(currency_id):
  """
  Delete A Currency
  """
  post = CurrencyModel.get_one_currency(currency_id)
  if not post:
    return custom_response({'error': 'post not found'}, 404)
  data = currency_schema.dump(post).data
  
  post.delete()
  return custom_response({'message': 'deleted'}, 204)
  

def custom_response(res, status_code):
  """
  Custom Response Function
  """
  return Response(
    mimetype="application/json",
    response=json.dumps(res),
    status=status_code
  )

